package cn.stylefeng.guns.core.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.ss.usermodel.Cell;

/**
 * @author zhucx
 */
public class DateUtil {
	
	/**
	 * 通过时间秒毫秒数判断两个时间的间隔
	 * @param date1
	 * @param date2
	 * @return
	 */
	 public static int differentDaysByMillisecond(Date date1,Date date2){
		 int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));
		 return days;
	 }
	 
	/**
	 * 传入生产日期、保质期，获取到期日期
	 * @param detailedDate
	 * @param goodsWarranty
	 * @return
	 */
	public static String getDaoQiDate(String detailedDate, int goodsWarranty) {
		 Calendar c = Calendar.getInstance();
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		 Date date = null;
		 try{
			 date = sdf.parse(detailedDate);//初始日期
		 }catch(Exception e){
		 }
		 c.setTime(date);//设置日历时间
		 c.add(Calendar.DAY_OF_YEAR,goodsWarranty);//在日历的月份上增加6个月
		return sdf.format(c.getTime());
	}
	
	/**
	 * 获取传入月份yyyy-mm 的上个月份或下个月份
	 * @param lisdateYearmonth
	 * @param interval
	 * @return
	 */
	public static String getYearMonthByMonth(String lisdateYearmonth, int interval) {
		DateFormat format2 =  new SimpleDateFormat("yyyy-MM");
		Date date = new Date();
		if (!"now".equals(lisdateYearmonth)) {
			try{
			    date = format2.parse(lisdateYearmonth);
			}catch(Exception e){
			    e.printStackTrace();
			}
		}
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM");
		c.add(Calendar.MONTH, interval);
		String time = format.format(c.getTime());

		return time;
	}

	/**
	 * 判断是否存在 字母
	 * @param cardNum
	 * @return
	 */
	public static boolean judgeContainsStr(String str) {  
        String regex=".*[a-zA-Z]+.*";  
        Matcher m= Pattern.compile(regex).matcher(str);  
        return m.matches();  
    }  
	
	//获取单元格各类型值，返回字符串类型
    public static String getCellValueByCell(Cell cell) {
        //判断是否为null或空串
        if (cell==null || cell.toString().trim().equals("")) {
            return "";
        }
        String cellValue = "";
        int cellType=cell.getCellType();
        switch (cellType) {
        case Cell.CELL_TYPE_NUMERIC: // 数字
            short format = cell.getCellStyle().getDataFormat();
            if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                SimpleDateFormat sdf = null;  
                //System.out.println("cell.getCellStyle().getDataFormat()="+cell.getCellStyle().getDataFormat());
                if (format == 20 || format == 32) {  
                    sdf = new SimpleDateFormat("HH:mm");  
                } else if (format == 14 || format == 31 || format == 57 || format == 58) {  
                    // 处理自定义日期格式：m月d日(通过判断单元格的格式id解决，id的值是58)  
                    sdf = new SimpleDateFormat("yyyy-MM-dd");  
                    double value = cell.getNumericCellValue();  
                    Date date = org.apache.poi.ss.usermodel.DateUtil  
                            .getJavaDate(value);  
                    cellValue = sdf.format(date);  
                }else {// 日期  
                    sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
                }  
                try {
                    cellValue = sdf.format(cell.getDateCellValue());// 日期
                } catch (Exception e) {
                    try {
                        throw new Exception("exception on get date data !".concat(e.toString()));
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }finally{
                    sdf = null;
                }
            }  else {
                BigDecimal bd = new BigDecimal(cell.getNumericCellValue()); 
                cellValue = bd.toPlainString();// 数值 这种用BigDecimal包装再获取plainString，可以防止获取到科学计数值
            }
            break;
        case Cell.CELL_TYPE_STRING: // 字符串
            cellValue = cell.getStringCellValue();
            break;
        case Cell.CELL_TYPE_BOOLEAN: // Boolean
            cellValue = cell.getBooleanCellValue()+"";;
            break;
        case Cell.CELL_TYPE_FORMULA: // 公式
            cellValue = cell.getCellFormula();
            break;
        case Cell.CELL_TYPE_BLANK: // 空值
            cellValue = "";
            break;
        case Cell.CELL_TYPE_ERROR: // 故障
            cellValue = "ERROR VALUE";
            break;
        default:
            cellValue = "UNKNOW VALUE";
            break;
        }
        return cellValue;
    }
	
	public static String getHttpResponse(String allConfigUrl) {
        BufferedReader in = null;
        StringBuffer result = null;
        try {
             
            URI uri = new URI(allConfigUrl);
            URL url = uri.toURL();
            URLConnection connection = url.openConnection();
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Charset", "utf-8");
         
            connection.connect();
             
            result = new StringBuffer();
            //读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }

            return result.toString();
             
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
         
        return null;
    }

    /**
     * 调用对方接口方法
     * @param path 对方或第三方提供的路径
     * @param data 向对方或第三方发送的数据，大多数情况下给对方发送JSON数据让对方解析
     */
    public static String interfaceUtil(String path,String data) {
        try {
            URL url = new URL(path);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            PrintWriter out = null;
            //请求方式
            conn.setRequestMethod("GET");
//           //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); 
            //设置是否向httpUrlConnection输出，设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
            //最常用的Http请求无非是get和post，get请求可以获取静态页面，也可以把参数放在URL字串后面，传递给servlet，
            //post与get的 不同之处在于post的参数不是放在URL字串里面，而是放在http请求的正文内。
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            //发送请求参数即数据
            out.print(data);
            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
            StringBuffer str = new StringBuffer();
            String st = "";
            while ((st = br.readLine()) != null) {
            	str.append(st);
            }
            return str.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
		return "";
    }

	public static Date getLastDate(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MONTH, -1);
		return cal.getTime();
	}
	
    
	/**
	 * 得到工时
	 * @param endDate
	 * @param nowDate
	 * @return
	 * @throws ParseException
	 */
    public static String getDatePoorMin(String endDate, String nowDate) throws ParseException {

    	DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        Date d1 = df.parse(endDate);//结束时间
        Date d2 = df.parse(nowDate);//开始时间
        
    	// 获得两个时间的毫秒时间差异
    	BigDecimal diff = new BigDecimal(d1.getTime() - d2.getTime());
    	
    	BigDecimal a = new BigDecimal(1000);
    	BigDecimal b = new BigDecimal(60);
    	
    	BigDecimal miao = diff.divide(a);
    	
    	BigDecimal fenzhong = miao.divide(b,2,BigDecimal.ROUND_HALF_DOWN);
    	
    	BigDecimal hour = fenzhong.divide(b,2,BigDecimal.ROUND_HALF_DOWN);

    	return  hour+"";

    	}
	/**
	 * 得到分钟
	 * @param endDate
	 * @param nowDate
	 * @return
	 * @throws ParseException
	 */
    public static String getDatePoorMinfenzhong(String endDate, String nowDate) throws ParseException {

    	DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        Date d1 = df.parse(endDate);//结束时间
        Date d2 = df.parse(nowDate);//开始时间
        
    	// 获得两个时间的毫秒时间差异
    	BigDecimal diff = new BigDecimal(d1.getTime() - d2.getTime());
    	
    	BigDecimal a = new BigDecimal(1000);
    	BigDecimal b = new BigDecimal(60);
    	
    	BigDecimal miao = diff.divide(a);
    	
    	BigDecimal fenzhong = miao.divide(b,2,BigDecimal.ROUND_HALF_DOWN);
    	

    	return  fenzhong+"";

    	}
	
		/** 
	    * 获取过去第几天的日期 yyyy-MM-dd
	    * @param past 
	    * @return 
	    */  
	   public static String getPastDate(int past) {  
	       Calendar calendar = Calendar.getInstance();  
	       calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);  
	       Date today = calendar.getTime();  
	       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
	       String result = format.format(today);  
	       return result;  
	   }  
		
		/** 
	    * 获取指定日期过去第几天的日期 yyyy-MM-dd
	    * @param past 
	    * @return 
		 * @throws ParseException 
	    */  
	   public static String getPastDateZd(String datestr,int past) throws ParseException {  
	       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
	       Date date = format.parse(datestr);
	       Calendar calendar = Calendar.getInstance();  
	       calendar.setTime(date);
	       calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);  
	       Date today = calendar.getTime();  
	       String result = format.format(today);  
	       return result;  
	   }  
		
		/** 
	    * 获取几天后的日期 yyyy-MM-dd
	    * @param past 
	    * @return 
	    */  
	   public static String getPastDatej(int past) {  
	       Calendar calendar = Calendar.getInstance();  
	       calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);  
	       Date today = calendar.getTime();  
	       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
	       String result = format.format(today);  
	       return result;  
	   } 
		
		/** 
	    * 获取指定日期的下一天 yyyy-MM-dd
	    * @param past 
	    * @return 
	    */  
	   public static String getXdat(String cdate) {  
	       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
	       try {
	    	   Date temp = format.parse(cdate);
	    	   Calendar cld = Calendar.getInstance();
	    	   cld.setTime(temp);
	    	   cld.add(Calendar.DATE, 1);
	    	   temp = cld.getTime();
	    	   return format.format(temp);
			} catch (Exception e) {
				return null;
			}
	   }   
		
		/** 
	    * 获取当前日期 yyyy-MM-dd
	    * @param past 
	    * @return 
	    */  
	   public static String getDate() {  
	       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
	       return format.format(new Date());  
	   }   
		
		/** 
	    * 获取当前月份 yyyy-MM
	    * @param past 
	    * @return 
	    */  
	   public static String getMonth() {  
	       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");  
	       return format.format(new Date());  
	   }   
	   
		/** 
	    * 获取当前日期 yyyyMMdd
	    * @return
	    */  
	   public static String getDateBch() {  
	       SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");  
	       return format.format(new Date());  
	   }   
	   
		/** 
	    * 获取当前日期 yyyyMMdd
	    * @return
	    */  
	   public static String getDatesBch() {  
	       SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");  
	       return format.format(new Date());  
	   }

	/**
	 * 获取当前日期 yyyyMMdd
	 * @return
	 */
	public static String getDateHour() {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHH");
		return format.format(new Date());
	}


	/**
	    * 获取当前日期yyyy-MM-dd HH:mm:ss
	    * @param past 
	    * @return 
	    */  
	   public static String getDateS() {  
	       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
	       return format.format(new Date());  
	   }

	/**
	 * 格式化日期
	 * @param dt
	 * @param patten
	 * @return
	 */
	public static String DateFormat(Date dt,String patten) {
		SimpleDateFormat format = new SimpleDateFormat(patten);
		return format.format(dt);
	}

	public static String parseTimeZone(String dateString) {
	        String FORMAT_STRING = "yyyy-MM-dd";
	        String FORMAT_STRING2 = "EEE MMM dd HH:mm:ss z yyyy";
	        String[] REPLACE_STRING = new String[]{"GMT+0800", "GMT+08:00"};
	        String SPLIT_STRING = "(中国标准时间)";
	        try {
	            dateString = dateString.split(Pattern.quote(SPLIT_STRING))[0].replace(REPLACE_STRING[0], REPLACE_STRING[1]);
	            //转换为date
	            SimpleDateFormat sf1 = new SimpleDateFormat(FORMAT_STRING2, Locale.ENGLISH);
	            Date date = sf1.parse(dateString);
	            return new SimpleDateFormat(FORMAT_STRING).format(date);
	        } catch (Exception e) {
	            throw new RuntimeException("时间转化格式错误" + "[dateString=" + dateString + "]" + "[FORMAT_STRING=" + FORMAT_STRING + "]");
	        }
	    }
	   
		/** 
	    * 获取五位随机数
	    * @param  
	    * @return 
	    */  
	   public static String getRandomNumber() {  
	    	Random random = new Random();
	        int randomNumber = random.nextInt(90000) + 10000;
	       return randomNumber+"";  
	   }  
}
